package com.wbu.estatemanagement.controller;

import com.wbu.estatemanagement.common.MessageConstant;
import com.wbu.estatemanagement.common.Result;
import com.wbu.estatemanagement.common.StatusCode;
import com.wbu.estatemanagement.dao.CommunityMapper;
import com.wbu.estatemanagement.domain.Community;
import com.wbu.estatemanagement.domain.Repair;
import com.wbu.estatemanagement.domain.User;
import com.wbu.estatemanagement.service.RepairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/repair")
public class RepairController {
    @Autowired
    RepairService repairService;
    @Autowired
    CommunityMapper communityMapper;

    @PostMapping("/select")
    public Result getUserRepair(HttpSession httpSession){
        User user =(User) httpSession.getAttribute("user");
        Repair repair=repairService.findRepair(user.getId());
        if (repair!=null){
            return new Result(true, StatusCode.OK, MessageConstant.SUCCESS,repair);
        }
        return new Result(true, StatusCode.ERROR, MessageConstant.FAIL);

    }

    @PostMapping("/add")
    public Result add(@RequestBody Repair repair,HttpSession httpSession){
        User user =(User) httpSession.getAttribute("user");
        repair.setOwnerId(user.getId());
        String communityName = repair.getCommunityName();
        List<Community> communities = communityMapper.selectAll();
        List<Community> collect = communities.stream().filter(s -> s.getName().equals(communityName)).collect(Collectors.toList());
        if (collect.isEmpty()){
            System.out.println("不存在该社区");
        }
        Community community = collect.get(0);
        repair.setCommunityId(community.getId());
        Boolean add = repairService.addRepair(repair);
        if (add==true){
            return new Result(true,StatusCode.OK,MessageConstant.SUCCESS,repair);
        }
        return new Result(false,StatusCode.ERROR,MessageConstant.FAIL);
    }

}
